<?php
/**
 * Created by JetBrains PhpStorm.
 * User: xiaoyan
 * Date: 15-5-4
 * Time: 下午1:56
 * To change this template use File | Settings | File Templates.
 */
class User extends BaseController{

    public function init()
    {
        $this->addRoute('/user.list','index');
        $this->addRoute('/user.exists','exists');
        $this->addRoute('/user.add','saveUser');
        $this->addRoute('/user.group.select','viewSelectGroup');
        $this->addRoute('/user.select','viewSelectUser');
        $this->addRoute('/user.view.{action}','showView');
        $this->addRoute('/user.action.login','userLogin');
        $this->addRoute('/user/manageUser','manageUser');
        $this->addRoute('/user.status.{status}','changeStatus');
        $this->addRoute('/user.set.group','setGroup'); //设置分组
    }
    public function userLogin(){
        $login_name = $this->getInput()->post('login_name');
        $login_pass = $this->getInput()->post('login_pass');
        $uid = DB()->table('user')->where(array(
            'AND' => array(
                'login_name' => $login_name,
                'login_pass' => $login_pass
            )
        ))->get();
        if($uid){
            $_SESSION['osw_uid'] = $uid['uid'];
            DB()->update('user',array('last_login_time'=>REQ_TIME,'login_count'=>$uid['login_count']+1),array('uid'=>$uid['uid']));
            ajaxSuccess($uid['uid']);
        }
        ajaxResponse(1,'用户名或密码错误');
    }
    public function  setGroup(){
        $id = $this->getInput()->get('id');
        $ids = explode(',',$id);
        $users = DB()
            ->field('uid')
            ->table('user')
            ->where(array('uid'=>$ids))
            ->select();
        if(count($ids) != count($users)){
            ajaxResponse(1,'设置分组失败(未找到个别用户)',$ids);
        }
        $group_id = $this->getInput()->post('group_id');
        if(!$group_id){ajaxResponse(1,'设置分组失败(未找到分组)');}
        $groupData = DB()->table('auth_group')->where('id',$group_id)->get();
        if(!$groupData){ajaxResponse(1,'设置分组失败(未找到分组)');}
        DB()->begin();
        $table_pre = $this->getConfig('db_config')->getConfig('db_prefix')->getValue();
        try{
            foreach($ids as $uid){//设置用户分组
                $querySQL = "replace into {$table_pre}auth_group_access (uid,group_id) values({$uid},{$group_id})";
                DB()->exec($querySQL);
            }
            DB()->commit();
        }catch (DBException $e){
            DB()->rollback();
            ajaxResponse(3,'设置分组失败(更新数据失败)',DB()->all_query());
        }
        ajaxSuccess(array('action'=>'close',));
    }

    function showView($action){
        $user = null;
        $act = 'insert';
        $render = 'user.'.$action;
        if($action == 'edit'){
            $render = 'user.add';
            if($action == 'edit'){
                $act = 'update';
                $uid = $this->getInput()->get('uid');
                if(!$uid){
                    $this->message('您要修改什么用户信息');
                }
                $user = DB()->table('user')->where('uid',$uid)->get();
                if(!$user){
                    $this->message('没有找到要修改的用户信息');
                }
                unset($user['login_pass']);
            }
        }
        $this->render($render,array(
            'user'=>$user,
            'act' =>$act
        ));
    }

    public function changeStatus($status){
        $id = $this->getInput()->post('id');
        if(!$id || count($id) == 0) ajaxResponse(1,'请选择要操作的用户');
        $stateData = array(
            'disabled' => DataState::$disable,
            'enabled' => DataState::$enable,
            'delete' => DataState::$invalid
        );
        if(!isset($stateData[$status])) ajaxResponse(2,'不能将用户设置为此状态');
        try{//尝试更新
            DB()->update('user',array('state'=>$stateData[$status]),array('uid'=>$id));
            ajaxSuccess();
        }catch (DBException $e){
            ajaxResponse(2,'设置用户状态失败');
        }
    }
    public function  saveUser(){
        $act = $this->getInput()->get('act');
        $backUrl = 'user.list';
        if($act && in_array($act,array('insert','update'))){

            $checkConf = array(array('login_name',1,'请填写登录用户名'));
            if($act == 'insert'){
                $checkConf[] = array('login_pass',2,'请填写登录密码');
                $checkConf[] = array('login_pass_re',3,'请再次填写登录密码');
            }else{
                $checkConf[] = array('uid',2,'修改数据有错误,请重试');
            }
            $saveData = $this->checkDataNull($checkConf);
            $this->getPostData($saveData,'nick_name');

            if(isset($saveData['login_pass']) && $saveData['login_pass'] != $saveData['login_pass_re']){
                ajaxResponse(4,'两次填写的密码不一致');
            }
            //不用保存第二次密码
            unset($saveData['login_pass_re']);
            $data = array('url'=>$backUrl);

            if($act == 'insert'){
                $user = DB()->table('user')->where('login_name',$saveData['login_name'])->get();
                if($user){
                    ajaxResponse(6,'该登录名已经存在');
                }
                $uid = $this->ajaxBasicInsert('user',$saveData);
            }else{
                $this->getPostData($saveData,'uid');
                $uid = $saveData['uid'];
                unset($saveData['uid']);
                $user = DB()->table('user')->where('uid',$uid)->get();
                if(!$user) { //查询是否已经存在用户
                    ajaxResponse(6,'没有找到要修改的用户信息');
                }
                if($this->input()->post('login_pass')){
                    $this->getPostData($saveData,'login_pass,login_pass_re');
                }
                if(isset($saveData['login_pass'])){
                    if($saveData['login_pass'] != $saveData['login_pass_re']){
                        ajaxResponse(4,'两次填写的密码不一致');
                    }
                    unset($saveData['login_pass_re']);
                }
                $this->ajaxBasicUpdate('user',$saveData,array('uid'=>$uid));
            }
            ajaxSuccess($data);
        }
        ajaxResponse(-1,'错误的请求');
    }

    public function viewSelectGroup(){
        $u_ids = $this->getInput()->get('id');
        if($u_ids){
            $u_ids = explode(',',$u_ids);
        }
        if(!$u_ids || count($u_ids) == 0){
            $this->message('请选择要设置的用户',null,true);
        }
        $user = DB()
            ->table('user')
            ->field('uid,nick_name')
            ->where(array('uid'=>$u_ids))
            ->select();
        $usersList = array_keys(array_value_toKey($user,'nick_name'));
        $usersList = implode(',',$usersList);
        $tablePre = $this->getConfig('db_config')->getConfig('db_prefix')->getValue();
        $querySQL = "select * from {$tablePre}auth_group g
left join (
SELECT
		group_id,
		count(1) AS user_count
	FROM
		{$tablePre}auth_group_access
	GROUP BY
		group_id
) as gd on g.id = gd.group_id";
        $group = DB()->fetchAll($querySQL);
        $showMore = array();
        $this->render('user.group_select',array(
            'groupList'=>$group,
            'user_list'=>$user,
            'user_ids'=>implode(',',$u_ids),
            'userList'=>$usersList
        ));
    }
    public function viewSelectUser(){
        $uid = $this->getUserId();
        $list = DB()
            ->field('g.title,a.group_id,u.nick_name,u.uid')
            ->table('user u')
            ->join(array(
                '[><]auth_group_access#a'=>array('u.uid' =>'a.uid'),
                '[><]auth_group#g'=>array('g.id' =>'a.group_id'),
            ))
            ->where(array(
                'u.uid[!]' => $uid
            ))
            ->where('g.alias',array('zxs','zxszg'))
            ->select();
        $userList = array();
        foreach($list as $u){
            if(!isset($userList[$u['group_id']])) $userList[$u['group_id']] = array(
                'group_name' => $u['title'],
                'user_list' => array()
            );
            $userList[$u['group_id']]['user_list'][] = $u;
        }

        if($this->input()->get('show_more_date') == 'date'){
            $showMore['more_date'] = true;
        }
        $this->render('user.user_select',array(
            'userList'=>$userList,
            'showMore' => $showMore
        ));
    }
    public function index(){
        list($page,$size,$start) = $this->getPageAndSize(8);
        $where = array(
            'AND' => array('1'=>'1')
        );
        $kw = $this->getInput()->get('nickname');
        if($kw){
            $where['LIKE']['OR'] = array(
                'nick_name'=>$kw,
                'login_name'=>$kw
            );
        }
        $list = DB()
            ->field('g.title,u.*')
            ->table('user u')
            ->join(array(
                '[>]auth_group_access#a'=>array('u.uid' =>'a.uid'),
                '[>]auth_group#g'=>array('g.id' =>'a.group_id'),
            ))
            ->where($where)
            ->limit($start,$size)
            ->select();
        $totalCount = DB()->count('user',$where);
        $pageString = $this->createWindowPageLink('user.list',$totalCount,$size);
        $this->render('user.list',array(
            'user_list'=>$list,
            'kw'=>$kw,
            'totalCount'=>$totalCount,
            'pageString'=>$pageString,
        ));
    }

    public function manageUser(){
        var_dump($this->verifyPermission('UserAddButton,UserEdit',2));
        echo $this->getInput()->get('s');
    }

    public function exists(){
        $loginName = $this->getInput()->get('login_name');
        $uid = $this->getInput()->get('uid');
        $user = DB()->table('user')
            ->where('login_name',$loginName)
            ->get();
        if(!$user) ajaxSuccess();
        if($uid && $uid == $user['uid']) ajaxSuccess();
        ajaxResponse(1,'该登录名已经存在');
    }
}